import express from "express";
import { exec, type ChildProcess } from "child_process";
import bodyParser from "body-parser";
import { validateCommand } from "./validator";
import type { AutomationCommand } from "./types";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.use(bodyParser.json());

const PORT = process.env.PORT || 3000;
console.log(PORT, process.env.PORT);

app.post("/automation", async (req, res) => {
  try {
    const command = req.body as AutomationCommand;

    const validationError = validateCommand(command);
    if (validationError) {
      return res.status(400).json({ error: validationError });
    }
    //构建命令
    const playwrightCommand = [
      "npx playwright test",
      command.project ? `--project=${command.project}` : "",
      command.testFile ? `"${command.testFile}"` : "",
      command.testTitle ? `--grep="${command.testTitle}"` : "",
      command.debug ? "--debug" : "",
    ]
      .filter(Boolean)
      .join(" ");

    const envVars = {
      ...process.env,
      COMMAND_TYPE: command.type || "test",
      HEADLESS: command.ui ? "false" : "true",
      ...command.env,
    };

    let childProcess: ChildProcess;
    try {
      childProcess = exec(playwrightCommand, { env: envVars });
    } catch (error) {
      return res.status(500).json({ error: `执行命令失败: ${error}` });
    }

    let output = "";
    let error = "";

    childProcess.stdout?.on("data", (data) => {
      output += data;
    });

    childProcess.stderr?.on("data", (data) => {
      error += data;
    });

    childProcess.on("close", (code) => {
      res.json({
        success: code === 0,
        output,
        error: error || undefined,
        command: playwrightCommand,
      });
    });
  } catch (err) {
    res.status(500).json({ error: String(err) });
  }
});

app.listen(PORT, () => {
  console.log(`自动化测试服务器运行在端口 ${PORT}`);
});
